#!/bin/bash

# Zawiera poprawke konfiguracji dhcp.
# Poprawiono eksport zmiennych.
# Testowano na Ubuntu Server 12.04.4 LTS.
# Skrypt zatwierdzono 8 marca.
# Wprowadzono usprawnienia w funkcjonowaniu kreatora Active Directory.

# UWAGA!!!!! Zmienna domain moze miec problem z przetworzeniem dlugich zmiennych!
# Skrypt przystosowany jest do nazw domenowych o nastepujacej maksymalnej dlugosci : xxx.yyyy.zzzz np. ak-test.local.net.

# Skrypt odwoluje sie do innych elementow zewnetrznych (np. paczka DEB Webmina).
# Przygotowywana jest wersja skryptu kompatybilna z systemem Debian 7.

#Haslo konta administrator: zaq!2wsx

#########FUNCTION ZONE!########################
		function hello {
		setterm -background blue -foreground white
		clear
		echo "A. Kastrau 2013-2014."
		echo "====================="
		echo ""
		echo 'Nazwa kodowa "Ogólniak" - wersja 1.18g_beta'
		echo  ""
		echo "Edycja Zima 2014."
		echo ""
		echo ""
		echo "Trwa przygotowywanie serwera do pierwszego uzycia..."
		sleep 5
		}

function pause {
read -p "Nacisnij [ENTER], aby kontynuowac..."
}
		
	function fix {
		echo "Poprawianie GRUB'a..."
		cat > /etc/default/grub << EOF
GRUB_DEFAULT=0
#GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=6
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootdelay=60"
GRUB_CMDLINE_LINUX="quiet"

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command vbeinfo
GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"
EOF
		echo ""
		echo "Usuwanie bledu karty graficznej..."
		echo "GRUB_GFXMODE=640x480" >> /etc/default/grub
		echo 'GRUB_INIT_TUNE="480 440 1"' >> /etc/default/grub
		echo ""
		echo "Konfiguruje system... "
		update-grub
		sleep 2
		echo "OK!" >> /root/.setup/fix
		echo "Gotowe!"
		echo ""
		}
	function network_setup {
		clear
		echo "Teraz zostana skonfigurowane interfejsy sieciowe"
		echo ""
		echo "Interfejs eth0 - Internet, eth1 - IntraNet"
		echo "==========================================="
		export if0_ip=192.168.0.2
		export if0_gateway=192.168.0.1
		export if0_dns1=194.204.152.34
		export if0_dns2=194.204.159.1
		
		export if1_ip=192.168.16.2
		export if1_network=192.168.16.0
		
		host=serwer
		export domain=lo1.net
		
		echo "Wykryto plik z ustawieniami konfiguracji sieci!"
		echo ""
		echo "Dane o konfiguracji sieci z pliku:"
		echo "Interfejs eth0: "
		echo ""
		echo "Adres IP: $if0_ip"
		echo "Brama domyslna: $if0_gateway"
		echo "DNS1: $if0_dns1"
		echo "DNS2: $if0_dns2"
		
		echo ""
		echo "Interfejs eth1: "
		echo "Adres IP: $if1_ip"
		echo "Adres sieci: $if1_network"
		echo ""
		echo "Nazwa hosta: $host"
		echo "Nazwa domeny: $domain"
		read -p "Czy te dane sa poprawne? [T/N]: " ans 
		case "$ans" in
			"T") set_network ;;
			"N") ch_net ;;
			"t") set_network ;;
			"n") ch_net ;;
			*) network_setup
		esac
			
	}
	
	function set_network {
		
		cat >> /etc/bash.bashrc << EOF
export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts

export if0_ip=192.168.0.2
export if0_gateway=192.168.0.1
export if0_dns1=194.204.152.34
export if0_dns2=194.204.159.1

export if1_ip=192.168.16.2
export if1_network=192.168.16.0

export host=serwer
export domain=lo1.net
EOF
########################VARS in txt####################
	cat >> /setup/vars << EOF
export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts

export if0_ip=192.168.0.2
export if0_gateway=192.168.0.1
export if0_dns1=194.204.152.34
export if0_dns2=194.204.159.1

export if1_ip=192.168.16.2
export if1_network=192.168.16.0

export host=serwer
export domain=lo1.net
EOF
		
##########################################################
export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts

export if0_ip=192.168.0.2
export if0_gateway=192.168.0.1
export if0_dns1=194.204.152.34
export if0_dns2=194.204.159.1

export if1_ip=192.168.16.2
export if1_network=192.168.16.0

export host=serwer
export domain=lo1.net
		
		echo ""
		echo "Zapisuje konfiguracje..."
		cp /setup/iptables.up.rules /etc/
		echo "auto eth0 eth1 lo" > /etc/network/interfaces
		echo "iface lo inet loopback" >> /etc/network/interfaces 
		echo "iface eth0 inet static" >> $file_if
		echo "address $if0_ip" >> $file_if
		echo "gateway $if0_gateway" >> $file_if
		echo "dns-nameservers $if0_dns1 $if0_dns2" >> $file_if
		echo "post-up iptables-restore < /etc/iptables.up.rules" >> $file_if
		echo "" >> $file_if
		echo "iface eth1 inet static" >> $file_if
		echo "address $if1_ip" >> $file_if
		
		
		echo $host > $file_hostname
		echo "127.0.0.1	localhost" > $file_hosts
		echo "127.0.1.1	$host" >> $file_hosts
		echo "$if1_ip $host.$domain $host" >> $file_hosts
		
		echo ""
		echo "Resetuje interfejsy..."
		sleep 3
		/etc/init.d/networking restart
		sleep 5 
		setterm -background blue -foreground white
		clear
		test_net
	}
	
	function ch_net {
	
	    setterm -background blue -foreground white
		echo ""
		echo "Podaj nowa konfiguracje interfejsow..."
		echo "Interfejs eth0:"
		read -p "Adres IP: " if0_ip
		read -p "Brama domyslna: " if0_gateway
		read -p "DNS1: " if0_dns1
		read -p "DNS2: " if0_dns2
		echo ""
		echo "Interfejs eth1:"
		read -p "Adres IP: " if1_ip
		read -p "Adres sieci: " if1_network
		echo ""
		read -p "Nazwa hosta: " host
		read -p "Nazwa domeny: " domain
		
		cat >> /etc/bash.bashrc << EOF
export if0_ip=$if0_ip
export if0_gateway=$if0_gateway
export if0_dns1=$if0_dns1
export if0_dns2=$if0_dns2
export if1_ip=$if1_ip
export if1_network=$if1_network
export domain=$domain
export host=$host

export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts
EOF
		
export if0_ip=$if0_ip
export if0_gateway=$if0_gateway
export if0_dns1=$if0_dns1
export if0_dns2=$if0_dns2
export if1_ip=$if1_ip
export if1_network=$if1_network
export domain=$domain
export host=$host

export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts

##########VARS in txt#######################
cat >> /setup/vars << EOF
export if0_ip=$if0_ip
export if0_gateway=$if0_gateway
export if0_dns1=$if0_dns1
export if0_dns2=$if0_dns2
export if1_ip=$if1_ip
export if1_network=$if1_network
export domain=$domain
export host=$host

export file_if=/etc/network/interfaces
export file_hostname=/etc/hostname
export file_hosts=/etc/hosts
EOF
##################################
		
		
		echo ""
		echo "Zapisuje konfiguracje..."
		cp /setup/iptables.up.rules /etc/
		echo "auto eth0 eth1 lo" > /etc/network/interfaces
		echo "iface lo inet loopback" >> /etc/network/interfaces 
		echo "iface eth0 inet static" >> $file_if
		echo "address $if0_ip" >> $file_if
		echo "gateway $if0_gateway" >> $file_if
		echo "dns-nameservers $if0_dns1 $if0_dns2" >> $file_if
		echo "post-up iptables-restore < /etc/iptables.up.rules" >> $file_if
		echo "" >> $file_if
		echo "iface eth1 inet static" >> $file_if
		echo "address $if1_ip" >> $file_if
		
		echo $host > $file_hostname
		echo "127.0.0.1	localhost" > $file_hosts
		echo "127.0.1.1	$host" >> $file_hosts
		echo "$if1_ip $host.$domain $host" >> $file_hosts
		
		echo ""
		echo "Skrypt zresetuje interfejsy sieciowe..."
		pause
		sleep 3
		/etc/init.d/networking restart
		sleep 5
		test_net
	}
	
	function test_net {
		clear
		if [ -f /root/.setup/net_ok ]
			then
				sys_prep
			else check_net
		fi
	}
	function check_net {
		echo "Zaraz rozpocznie sie test lacza internetowego."
		echo "Jesli host zdalny odpowie na pakiety ICMP Echo request, to znaczy, ze lacze zostalo prawidlowo skonfigurowane."
		echo ""
		echo "Aby przerwac test lacza nacisnij Ctrl+C"
		echo ""
		pause
		ping wp.pl
		echo ""
		interact_net	
	}
	function interact_net {
		
		read -p "Czy serwer odpowiedzial na ping? [T/N]: " ans_net
		case "$ans_net" in
		"T") ok_net ;;
		"t") ok_net ;;
		"N") fail_net ;;
		"n") fail_net ;;
		*) interact_net
		esac
			}
	function ok_net {
		echo "OK!" >> /root/.setup/net_ok
		echo "OK!" >> /root/.setup/net
		clear
		echo "Instalacja serwera cz.2..."
		sleep 3
		sys_prep
	}
	
	function fail_net {
		setterm -background red -foreground white
		clear
		echo "Zostanie uruchomiony system bez obslugi sieci!"
		echo "Popraw ustawienia i uruchom ponownie system, aby dokonczyc instalacje..."
		echo ""
		pause
		exit 1
	}
	
	function sys_prep {
		source /setup/vars
		echo ""
		echo "Zostana teraz zauktalizowane repozytoria oprogramowania,"
		echo "a nastepnie system bazowy."
		echo ""
		DEBIAN_FRONTEND=noninteractive
		export DEBIAN_FRONTEND=noninteractive
		sleep 5
		apt-get update
		apt-get upgrade -y -qq
		echo ""
		echo "Aktualizacja zakonczona..."
		sleep 3
	}
		
	function install_deps {
		source /setup/vars
		echo "Instalacja potrzebnych skladnikow..."
		echo ""
		apt-get install -y -qq xorg xfce4 perl libapt-pkg-perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions python mousepad gpm git firefox gdebi build-essential libacl1-dev libattr1-dev \
   libblkid-dev libgnutls-dev libreadline-dev python-dev \
   python-dnspython gdb pkg-config libpopt-dev libldap2-dev \
   dnsutils libbsd-dev attr krb5-user docbook-xsl libcups2-dev rcconf dialog ssh isc-dhcp-server
		echo ""
		echo ""
		sleep 10
	}
	
	function install_webmin {
		source /setup/vars
		sleep 4
		clear
		echo "Zaraz rozpocznie sie instalacja webmina..."
		echo "Po instalacji wystarczy wejsc na adres https://nazwa_hosta:10000."
		echo ""
		sleep 10
		dpkg -i /setup/webmin.deb
		echo ""
		echo ""
		echo "OK!" >> /root/.setup/pkg
		sleep 15
	}
	
	function samba_prepare {
		echo ""
		echo "Zaraz zostanie pobrana najnowsza wersja samby!"
		echo "Moze to potrwac do kilku minut..."
		echo ""
		sleep 10
		cd /root/
		wget http://www.samba.org/samba/ftp/samba-latest.tar.gz
		echo ""
		echo ""
		sleep 3
		tar -xvzf samba-latest.tar.gz
		sleep 3
		echo "OK!" >> /root/.setup/pre_samba
	}
	
	function samba_comp {
		echo ""
		echo "Kompilacja kontrolera potrwa jakies 1,5h!"
		echo ""
		sleep 10
		cd /root/samba*
		./configure
		make
		make install
		echo "OK!" >> /root/.setup/samba_install
	}

	function samba_post {
		source /setup/vars
		dialog --backtitle "Konfiguracja systemu." --msgbox "Za chwile skrypt zapyta sie o kilka istotnych informacji..." 10 30
		clear
		echo ""
		echo "#!/bin/sh -e" > /etc/rc.local
		echo 'echo "Uruchamiam kontroler domeny..."' >> /etc/rc.local
		echo "/usr/local/samba/sbin/samba" >> /etc/rc.local
		echo "exit 0" >> /etc/rc.local

		echo "Podaj zakres dhcp w postaci xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy" 
		read -p "Podaj zakres: " dhcp_range
		
		echo ""
		echo "Uruchamianie kreatora AD DS..."
		realm=$domain
		addom=${domain%%.*}
		echo ""

		echo 'export PATH=$PATH:/usr/local/samba/sbin:/usr/local/samba/bin' >> /etc/bash.bashrc
		echo ""
		/usr/local/samba/bin/samba-tool domain provision --host-ip=$if1_ip --adminpass='zaq!2wsx' --realm=$realm --domain=$addom
		
		rm /scripts/iptables*
		
		mv /usr/local/samba/private/krb5.conf /etc/
	
		echo "Tworze katalog profile..."
		mkdir /var/profile
		echo ""
		echo "Udostepniam zasoby..."
		echo ""
		echo "" >> /usr/local/samba/etc/smb.conf
		echo "[profile]" >> /usr/local/samba/etc/smb.conf
		echo "Read only = no" >> /usr/local/samba/etc/smb.conf
		echo "Path = /var/profile" >> /usr/local/samba/etc/smb.conf
		
		host="$(tr '[a-z]' '[A-Z]' <<< "$host")"
		upp="$(echo "$host")"
		sed -i "s/UBUNTU/$upp/g" /usr/local/samba/etc/smb.conf
 
		echo ""
		echo "Ustawiam interfejsy sieciowe i serwer DNS..."
		 
		file_if=/etc/network/interfaces
		file_hostname=/etc/hostname
		file_hosts=/etc/hosts
		
		echo "Zapisuje konfiguracje..."
		echo "auto eth0 eth1 lo" > /etc/network/interfaces
		echo "iface lo inet loopback" >> /etc/network/interfaces 
		echo "iface eth0 inet static" >> $file_if
		echo "address $if0_ip" >> $file_if
		echo "netmask $if0_netmask" >> $file_if
		echo "gateway $if0_gateway" >> $file_if
		echo "network $if0_network" >> $file_if
		echo "broadcast $if0_broadcast" >> $file_if
		echo "dns-nameservers $if1_ip $if0_dns1" >> $file_if
		echo "post-up iptables-restore < /etc/iptables.up.rules" >> $file_if
		echo "" >> $file_if
		echo "iface eth1 inet static" >> $file_if
		echo "address $if1_ip" >> $file_if
		echo "netmask $if1_netmask" >> $file_if
		echo "network $if1_network" >> $file_if
		echo "broadcast $if1_broadcast" >> $file_if

		echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
		
		echo ""
		echo "Zaraz rozpocznie sie koncowa konfiguracja systemu..."
		echo ""
		pause

		echo "Konfiguruje automatyczne aktualizacje zabezpieczen..."
		sleep 5
		DEBIAN_FRONTEND=dialog
		echo ""
		dpkg-reconfigure unattended-upgrades
		
		echo "Wybierz uslugi, ktore chcesz wylaczyc..."
		sleep 5
		rcconf
		echo ""
		
		echo "Kopiuje skrypty do NETLOGON..."
		cp /scripts/* /usr/local/samba/var/locks/sysvol/$domain/scripts/
		sleep 3
		
		echo ""
		echo ""
		echo "Zapisuje koncowa konfiguracje..."
		rm -f /etc/motd
		touch /etc/motd
		echo "" >> /etc/motd
		echo "Glowny serwer sieci $domain !" >> /etc/motd
		echo "==============================" >> /etc/motd
		echo "A. Kastrau, W. Grochowski. Szkolna siec komputerowa." >> /etc/motd
		echo "" >> /etc/motd
		echo "Witamy!" >> /etc/motd
		echo "" >> /etc/motd
		echo ""
		
		service isc-dhcp-server stop
		service isc-dhcp-server6 stop
		echo ""
		echo ""
		
		echo "Zaraz zostanie skonfigurowany serwer DHCP..."
		sleep 3
		
		
		echo ""
		echo "Zapisuje konfiguracje serwera DHCP..."
		
		cat > /etc/dhcp/dhcpd.conf << EOF

#
# Sample configuration file for ISC dhcpd for Debian
#
# Attention: If /etc/ltsp/dhcpd.conf exists, that will be used as
# configuration file instead of this file.
#
#

# The ddns-updates-style parameter controls whether or not the server will
# attempt to do a DNS update when a lease is confirmed. We default to the
# behavior of the version 2 packages ('none', since DHCP v2 didn't
# have support for DDNS.)
ddns-update-style none;

# option definitions common to all supported networks...
option domain-name "$domain";
option domain-name-servers $if1_ip;

default-lease-time 600;
max-lease-time 7200;

# If this DHCP server is the official DHCP server for the local
# network, the authoritative directive should be uncommented.
#authoritative;

# Use this to send dhcp log messages to a different log file (you also
# have to hack syslog.conf to complete the redirection).
log-facility local7;

# No service will be given on this subnet, but declaring it helps the 
# DHCP server to understand the network topology.

#subnet 10.152.187.0 netmask 255.255.255.0 {
#}

# This is a very basic subnet declaration.

#subnet 10.254.239.0 netmask 255.255.255.224 {
#  range 10.254.239.10 10.254.239.20;
#  option routers rtr-239-0-1.example.org, rtr-239-0-2.example.org;
#}

# This declaration allows BOOTP clients to get dynamic addresses,
# which we don't really recommend.

#subnet 10.254.239.32 netmask 255.255.255.224 {
#  range dynamic-bootp 10.254.239.40 10.254.239.60;
#  option broadcast-address 10.254.239.31;
#  option routers rtr-239-32-1.example.org;
#}

# A slightly different configuration for an internal subnet.
#subnet 10.5.5.0 netmask 255.255.255.224 {
#  range 10.5.5.26 10.5.5.30;
#  option domain-name-servers ns1.internal.example.org;
#  option domain-name "internal.example.org";
#  option routers 10.5.5.1;
#  option broadcast-address 10.5.5.31;
#  default-lease-time 600;
#  max-lease-time 7200;
#}

# Hosts which require special configuration options can be listed in
# host statements.   If no address is specified, the address will be
# allocated dynamically (if possible), but the host-specific information
# will still come from the host declaration.

#host passacaglia {
#  hardware ethernet 0:0:c0:5d:bd:95;
#  filename "vmunix.passacaglia";
#  server-name "toccata.fugue.com";
#}

# Fixed IP addresses can also be specified for hosts.   These addresses
# should not also be listed as being available for dynamic assignment.
# Hosts for which fixed IP addresses have been specified can boot using
# BOOTP or DHCP.   Hosts for which no fixed address is specified can only
# be booted with DHCP, unless there is an address range on the subnet
# to which a BOOTP client is connected which has the dynamic-bootp flag
# set.
#host fantasia {
#  hardware ethernet 08:00:07:26:c0:a5;
#  fixed-address fantasia.fugue.com;
#}

# You can declare a class of clients and then do address allocation
# based on that.   The example below shows a case where all clients
# in a certain class get addresses on the 10.17.224/24 subnet, and all
# other clients get addresses on the 10.0.29/24 subnet.

#class "foo" {
#  match if substring (option vendor-class-identifier, 0, 4) = "SUNW";
#}

#shared-network 224-29 {
#  subnet 10.17.224.0 netmask 255.255.255.0 {
#    option routers rtr-224.example.org;
#  }
#  subnet 10.0.29.0 netmask 255.255.255.0 {
#    option routers rtr-29.example.org;
#  }
#  pool {
#    allow members of "foo";
#    range 10.17.224.10 10.17.224.250;
#  }
#  pool {
#    deny members of "foo";
#    range 10.0.29.10 10.0.29.230;
#  }
#}
# $domain IntraNet
subnet $if1_network netmask 255.255.255.0 {
	authoritative;
	range $dhcp_range;
	option routers $if1_ip;
	default-lease-time 86400;
	}
EOF

	dialog --backtitle "Informacja dla administratora." --msgbox 'Za chwile skrypt zakonczy swoja prace. Po restarcie, wykonaj nastepujace czynnosci: 1. Wykonaj ping np. ping wp.pl, 2. Wpisz komende kinit administrator, aby sprawdzic czy dziala serwer AD; 3.Sprawdz czy ruch "przeplywa" przez serwer (z poziomu klienta).' 15 75
	dialog --backtitle "Konfiguracja systemu." --msgbox 'UWAGA! W systemie istnieja 2 konta: root i user (hasla standardowe). Obecna konfiguracja zapory sieciowej nie jest bezpieczna! Nalezy ja bezzwlocznie dostosowac do wlasnych potrzeb!' 15 75
	}
	
	function clean {

		echo ""
		echo "Czyszczenie po instalacji..."
		echo ""
		rm -r -f /root/.setup/
		rm -r -f /setup/
		echo ""
		echo "Czyszczenie zakonczone!"
		echo ""
		pause
		reboot
	}
		
############END FUNCTION ZONE!###################

###########init!
clear
echo ""
echo "Czekaj..."
sleep 3
mkdir /root/.setup/


#####MAIN##########
hello

if [ -f '/root/.setup/fix' ]
then
	echo ''
	echo 'Poprawka zostala zainstalowana!'
else
fix
	sleep 3
	echo 'System zostanie uruchomiony ponownie...'
	reboot
fi
sleep 3
if [ ! -f '/root/.setup/net' ]
then
	network_setup
else
	test_net
fi

if [ -f '/root/.setup/pkg' ]
then
	clear
else
	install_deps
	install_webmin
fi

if [ -f '/root/.setup/pre_samba' ]
then
	echo ""	
else
	samba_prepare
fi

if [ -f '/root/.setup/samba_install' ]
then
	clear
else
	samba_comp
fi

samba_post

DEBIAN_FRONTEND=dialog

clean
reboot
